package com.qilin.hscs.controller;

import com.qilin.hscs.enums.ResultEnum;
import com.qilin.hscs.exception.SMException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by 10188 on 2018/5/4.
 */
@Controller
public class HSCSErrorController implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

    private static final Logger logger= LogManager.getLogger(HSCSErrorController.class.getName());


    @RequestMapping(value = ERROR_PATH)
    public void handleError(HttpServletRequest request) {
        logger.info("request_error");
        Map<String, Object> attributes = getAttributes(request, false);
        logger.info(attributes);
        Integer status = (Integer) attributes.get("status");
        if (status == 404) {
            throw new SMException(ResultEnum.NO_HANDLER);
        } else if (status == 500) {
            throw new SMException(ResultEnum.SERVER_ERROR);
        }
    }
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
    private Map<String, Object> getAttributes(HttpServletRequest request,
                                              boolean includeStackTrace) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        Map<String, Object> map = this.errorAttributes.getErrorAttributes(requestAttributes,includeStackTrace);
        String URL = request.getRequestURL().toString();
        map.put("URL", URL);
        return map;
    }
}
